package com.edu.tool.util;


import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
public class MsgUtil {
    static  Logger logger = LoggerFactory.getLogger(MsgUtil.class);


    static ConcurrentHashMap<String,Properties> propertyFileInMap = new ConcurrentHashMap<>() ;
    static String msgFileName = "msg";

    public static  Map<String,Object> retMsgMap( String msgkey) {
        return retMsgMap("",msgkey,"");
    }

    public static  Map<String,Object> retMsgMap( String msgkey,String msg) {
        return retMsgMap("",msgkey,msg);
    }

    public static  Map<String,Object> retMsgMap(String module,String msgkey,String msg){
        String fileName = msgFileName + module + ".properties";
        Properties msgps = propertyFileInMap.get(fileName);
        String msgKeyCode = msgkey + "_CODE";

        if (msgps == null ){
            msgps =  loadProps(fileName);
            propertyFileInMap.putIfAbsent(fileName,msgps);
        }

        HashMap m = new HashMap<String,Object>();
        String errCode = (String)msgps.get(msgKeyCode);
        m.put("error_code", errCode);

        if(StringUtils.isNotEmpty(msg)){
            m.put("error_message",msg);

        }
        else
        {
            String errMsg = (String)msgps.get(msgkey);
            m.put("error_message",errMsg);
        }

        return m;
    }


    private synchronized static  Properties  loadProps(String fileName) {
        Properties props = new Properties();
        InputStream in = null;
        try {
            in = MsgUtil.class.getClassLoader().getResourceAsStream(fileName);
            props.load(in);
        } catch (FileNotFoundException e) {
            logger.error("文件未找到" + fileName);

        } catch (IOException e) {
            logger.error(e.getMessage());

        } finally {
            try {
                if (null != in) {
                    in.close();
                }
            } catch (IOException e) {
                logger.error("文件流关闭出现异常"+ fileName);

            }
        }
        return props;
    }

    public static Map<String,Object> retMap(String obj_name, Object obj){
        Map<String,Object> m = new HashMap<>();

        m.put("error_code", 0);


        if(obj != null){
            m.put(obj_name, obj);
        }

        return m;

    }
}
